package com.shuimin.group.mid.time;

import com.shuimin.group.App;
import com.shuimin.group.constant.Config;
import com.shuimin.group.constant.GroupLifeCycle;
import com.shuimin.group.constant.GroupStatus;
import com.shuimin.group.logic.GroupLogic;
import com.shuimin.group.mid.message.SendType;
import com.shuimin.group.mid.message.TemplateMessage;
import com.shuimin.group.mid.redis.RedisGroupKey;
import com.shuimin.group.mid.redis.RedisKey;
import com.shuimin.group.mid.redis.RedisService;
import com.shuimin.group.mid.redis.RedisUtil;
import com.shuimin.group.model.group.Group;
import com.shuimin.group.model.sign.Sign;
import com.shuimin.group.service.GroupService;
import pond.common.S;
import java.util.*;

public class Task_MatchGroup extends TimerTask {

    @Override
    public void run() {

        List<Group>  updateGroupList = new ArrayList<>();
        List<Sign>   unsignList = new ArrayList<>();
        List<String> delKeyList = new ArrayList<>();
        List<String> groupKeyList = RedisService.getGroupKeys();
        S.echo("groupkeyList:", groupKeyList);

        S._for(groupKeyList).each(groupKey ->{
            String[] arr = groupKey.split(":");
            //state:place_id:time:group_id
            if (arr.length != RedisGroupKey.group_key.val())
            {
                S.echo(groupKey);
                return;
            }
            long create_type = new Integer(arr[RedisGroupKey.create_type.val()]);
            long book_time =  new Long(arr[RedisGroupKey.book_time.val()]);
            long max_num =  new Long(arr[RedisGroupKey.max_num.val()]);
            String group_id = arr[RedisGroupKey.group_id.val()];
            long delay = new Long( RedisUtil.hGetFieldVal(groupKey, "delay"));
            GroupLifeCycle groupLifeCycle = GroupLifeCycle.get( RedisUtil.hGetFieldVal(groupKey, RedisKey.GROUP_LIFE_CYCLE));
            long real_book_time = book_time + Config.ms(delay);
            String templateMsgKey = group_id+RedisKey.TEMPLATE_MSG;

            switch (groupLifeCycle)
            {
                case notify_delay:
                {
                    if (GroupLogic.isNotifyDelay(book_time, delay) )
                    {
                        //发送延时消息
                        String msgId = S.uuid.vid()+":"+templateMsgKey;
                        Map<String,String> msg = new HashMap<>();
                        msg.put("group_id", group_id);
                        msg.put("send_type", SendType.MULTIPLE.val());
                        msg.put("time", String.valueOf(S.now()));
                        msg.put("type", TemplateMessage.ACTIVITY_JOIN.id());
                        msg.put("text", "请5分钟内确认是否需要推迟，否则人数不足系统会取消该局");
                        if (RedisUtil.hAddOne(msgId,msg))
                        {
                            RedisUtil.enqueue(RedisKey.TO_DO_TEMPLATE_MSG,msgId);
                            groupLifeCycle = GroupService.next(groupLifeCycle);
                            RedisUtil.hSetFieldVal(groupKey, RedisKey.GROUP_LIFE_CYCLE,groupLifeCycle.val());
                        }
                    }
                    break;
                }
                case join_end:
                {
                    if (GroupLogic.isJoinEnd(real_book_time))
                    {
                        List<String> memberkeyList= RedisUtil.keys(group_id+"*"+ RedisKey.MEMBER);
                        long join_num = memberkeyList.size();
                        if (GroupLogic.isCreateOk(create_type, max_num, join_num))
                        {
                            //创建成功，无法退出以及取消局
                            groupLifeCycle = GroupService.next(groupLifeCycle);
                            RedisUtil.hSetFieldVal(groupKey, RedisKey.GROUP_LIFE_CYCLE,groupLifeCycle.val());
                        }
                        else {
                            //创建失败，取消局，通知全体成员
                            //设置数据库取消
                            String msgId = S.uuid.vid()+":"+templateMsgKey;
                            Map<String,String> msg = new HashMap<>();
                            msg.put("group_id", group_id);
                            msg.put("send_type", SendType.MULTIPLE.val());
                            msg.put("time", String.valueOf(S.now()));
                            msg.put("type", TemplateMessage.ACTIVITY_CANCEL.id());
                            msg.put("text", "人数不足，系统取消该局");
                            if (RedisUtil.hAddOne(msgId,msg)) {
                                RedisUtil.enqueue(templateMsgKey, msgId);
                                RedisUtil.hSetFieldVal(groupKey, RedisKey.GROUP_LIFE_CYCLE, GroupLifeCycle.game_over.val());
                                Group group = new Group();
                                group.setId(group_id);
                                group.set("group_status", GroupStatus.GROUP_STATUS_AUTO_CANCEL.val());
                                updateGroupList.add(group);
                            }
                        }
                    }
                    break;
                }
                case send_sign:
                {
                    if (GroupLogic.isSendSign(real_book_time))
                    {
                        //发送签到
                        String msgId = S.uuid.vid()+":"+templateMsgKey;
                        Map<String,String> msg = new HashMap<>();
                        msg.put("group_id", group_id);
                        msg.put("send_type", SendType.MULTIPLE.val());
                        msg.put("time", String.valueOf(S.now()));
                        msg.put("type", TemplateMessage.ACTIVITY_SIGN.id());
                        msg.put("text", "请5分钟内完成签到");
                        if (RedisUtil.hAddOne(msgId,msg)) {
                            RedisUtil.enqueue(templateMsgKey, msgId);
                            groupLifeCycle = GroupService.next(groupLifeCycle);
                            RedisUtil.hSetFieldVal(groupKey, RedisKey.GROUP_LIFE_CYCLE, groupLifeCycle.val());
                        }
                    }
                    break;
                }
                case calc_sign:
                {
                    if (GroupLogic.isCalcSign(real_book_time))
                    {
                        //统计签到
                        String signKey = RedisService.getKey(group_id, RedisKey.SIGN);
                        List<String> signMemberList = RedisUtil.sMembers(signKey);
                        List<String> memberList = RedisUtil.scanKey(group_id + "*" + RedisKey.MEMBER);
                        S._for(memberList).each(member -> {

                            if (signMemberList.contains(member))
                            {
                                //msg.put("send_type", SendType.SINGLE.val());
                                //todo 签到完成，则推送优惠消息，推送消息，更新数据库 is_handle 1
                                //RedisUtil.enqueue(templateMsgKey, TemplateMessage.ACTIVITY_END.id());
                                //msg.put("send_type", SendType.SINGLE.val());
                            }
                            else
                            {
                                Sign sign = new Sign();
                                sign.setId(S.uuid.vid());
                                sign.set("weixin_user_id", member);
                                sign.set("group_id", group_id);
                                sign.set("is_sign", "1");
                                sign.set("sign_time", String.valueOf(S.now()));
                                sign.set("is_handle", "1");
                                //todo 未签到是否发送信息
                                //msg.put("send_type", SendType.SINGLE.val());
                                unsignList.add(sign);
                            }
                        });
                        groupLifeCycle = GroupService.next(groupLifeCycle);
                        RedisUtil.hSetFieldVal(groupKey, RedisKey.GROUP_LIFE_CYCLE,groupLifeCycle.val());
                        Group group = new Group();
                        group.setId(group_id);
                        group.set("group_status", GroupStatus.GROUP_STATUS_FINISH.val());
                        updateGroupList.add(group);
                    }
                    break;
                }
                case send_feedback:{
                    if (GroupLogic.isSendFeedback(real_book_time))
                    {
                        //todo  签到完成一个小时则推送评价信息
                        //发送反馈
//                        String msgId = S.uuid.vid()+":"+templateMsgKey;
//                        Map<String,String> msg = new HashMap<>();
                        //msg.put("send_type", SendType.MULTIPLE.val());
//                        msg.put("group_id", group_id);
//                        msg.put("time", String.valueOf(S.now()));
//                        msg.put("type", TemplateMessage.ACTIVITY_FEEDBACK.id());
//                        msg.put("text", "请反馈用户体验");
//                        if (RedisUtil.hAddOne(msgId,msg)) {
//                            RedisUtil.enqueue(templateMsgKey, TemplateMessage.ACTIVITY_FEEDBACK.id());
                            groupLifeCycle = GroupService.next(groupLifeCycle);
                            RedisUtil.hSetFieldVal(groupKey, RedisKey.GROUP_LIFE_CYCLE, groupLifeCycle.val());
//                        }
                    }
                    break;
                }
                case game_over:
                {
                    List<String> msgKeys = RedisUtil.scanKey("*"+templateMsgKey);
                    if (msgKeys != null && msgKeys.size() >0)
                    {
                        //消息没有发完
                    }
                    else
                    {
                        //todo
                        delKeyList.addAll(RedisService.getAllKeysAboutGroup(group_id,groupKey));
                    }
                    break;
                }

            }

            if (!RedisUtil.delKeys(delKeyList))
            {
                S.echo("del failed"+delKeyList);
            }
            App.DB.post(t->{
                S._for(unsignList).each(item-> t.recordInsert(item));
                S._for(updateGroupList).each(item->t.recordUpdate(item));
            });
        });

    }
}